const user=require('../models/user.js');
//const jwt=require('koa-jwt')
const bcrypt=require('bcryptjs');
// const getUserInfo=function* () {
// 	const id=this.params.id;
// 	const result =yield user.getUserById(id);
// 	this.body=result
// }
const jsonwebtoken= require('jsonwebtoken');
const getUserInfo=async function(){
	const id=this.params.id;
	const result=await user.getUserById(id);
	this.body=result
}


const postUserAuth=async (ctx)=>{
	const data=ctx.request.body;	
	const userInfo=await user.getUserByName(data.name);
	if(userInfo!=null){
		if(!bcrypt.compareSync(data.password, userInfo.password)){		
			ctx.body={
				success:false,
				info:'密码错误'
			}
		}else{//密码正确
			const userToken={
				name:userInfo.username,
				id:userInfo.id
			}
			const secret='vue-koa-demo'// 指定密钥，这是之后用来判断token合法性的标志
			const token=jsonwebtoken.sign(userToken,secret)
			console.log('token:'+token)
			ctx.body={
				success:true,
				token:token
			}
		}
	}else{
		ctx.body={
			success:false,
			info:'用户不存在'
		}
	}
}
const createUser=async (ctx)=>{
	let data=ctx.request.body;
	let result=await user.createUser(data)
	ctx.body={
		success:true
	}
}
module.exports={
	getUserInfo,
	postUserAuth,
	createUser
}